package entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Entity @Table(name="USERS")
@NamedQueries({	
@NamedQuery(name = "User.selectByName", query = "SELECT u FROM User u WHERE u.name = :name"), 
@NamedQuery(name = "User.selectRolesCountByUserName", query = "SELECT COUNT(r) FROM User u JOIN u.roles r WHERE u.name = :name"),
@NamedQuery(name = "User.selectByPartName", query = "SELECT u FROM User u WHERE u.name LIKE :partname"), 
@NamedQuery(name = "User.selectByRoleAndUserPartName", query = "SELECT u FROM User u INNER JOIN u.roles r WHERE r.name = :roleName AND u.name LIKE :partname"), 
@NamedQuery(name = "User.selectUserListByUserPartNameWithNoRoles", query = "select u from User u WHERE u.name LIKE :partname AND u.roles IS EMPTY"),
})
public class User {

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="DEF_GEN")    
	@SequenceGenerator(name = "DEF_GEN", sequenceName = "USER_ID_SEQ", initialValue = 4, allocationSize=1)
	@Column(name = "USER_ID")
	private int id;
	
	@NotNull(message="{name.cannot.be.empty}")
	@Size(min=4, max=30, message="{invalid.length.4.30}")
	@Pattern(regexp = "[a-zA-Z0-9_-]+", message = "{must.contain.only.letters.or.numbers}")
	@Column(name = "NAME", unique = true) 
	private String name;
	
	@NotNull(message="{pass.cannot.be.empty}")	
	@Size(min=4, max=50, message="{invalid.length.4.50}")
	@Column(name = "PASS") 
	private String pass;
	
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(name = "USER_ROLES", 
			joinColumns = @JoinColumn(name = "USER_ID"),
			inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
	private List<Role> roles = new ArrayList<>();
	
	@OneToOne(mappedBy = "user", cascade = CascadeType.REMOVE)
    private Doctor doctor;
	
	public User() { }
	
	public User(String name, String pass) {
		this.name = name;
		this.pass = pass;
	}
	
	public int getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
	public String getPass() {
		return pass;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setPass(String pass) {
		this.pass = pass;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}
	
}